<template>
  <!--新增/编辑计划-->
  <vx-popup :title="dialogTitle" width="1000px" @close="cancelSubmit" :active.sync="dialogVisible"
    @confirmPopup="handleSubmit" @cancelPopup="cancelSubmit" clearable>
    <el-form :model="ruleForm"  ref="ruleForm" class="demo-ruleForm">
      <div class="insp-task-addPage-basic">
        <el-row justify="space-between" :gutter="20">
          <el-col :span="8">
            <el-form-item label="桥梁名称:" prop="name" label-width="95px">
              <el-select v-model="ruleForm.inspBridge" placeholder="请选择桥梁" size="small" style="width:100%"
                         @change="(event)=>handleBridgeChange(event)" clearable value-key="id">
                <el-option v-for="item in bridgeOptions" :key="item.id" :label="item.ownName" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检项 :" prop="inspType" label-width="95px">
              <el-select v-model="ruleForm.inspType" placeholder="请选择巡检类型" size="small" style="width:100%" clearable>
                <el-option label="日常巡检" :value="0"></el-option>
                <el-option label="定期巡检" :value="1"></el-option>
                <el-option label="特殊巡检" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="病害名称:" prop="name" label-width="95px">
              <el-select v-model="ruleForm.inspBridge" placeholder="请选择病害名称" size="small" style="width:100%"
                         @change="(event)=>handleBridgeChange(event)" clearable value-key="id">
                <el-option v-for="item in bridgeOptions" :key="item.id" :label="item.ownName" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <el-col :span="8">
            <el-form-item label="定量描述:" prop="name" label-width="95px">
              <el-input placeholder="请输入平米面积" v-model="taskName" size="small" style="width: 180px;" class="mRight10">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="巡检人:" prop="name" label-width="95px">
              <el-select v-model="ruleForm.inspBridge" placeholder="请输入巡检人" size="small" style="width:100%"
                         @change="(event)=>handleBridgeChange(event)" clearable value-key="id">
                <el-option v-for="item in bridgeOptions" :key="item.id" :label="item.ownName" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="严重程度 :" prop="inspType" label-width="95px">
              <el-select v-model="ruleForm.inspType" placeholder="请选择严重程度" size="small" style="width:100%" clearable>
                <el-option label="一般" :value="0"></el-option>
                <el-option label="严重" :value="1"></el-option>
                <el-option label="非常严重" :value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <el-col :span="8">
            <el-form-item label="新旧病害 :" prop="inspType" label-width="95px">
              <el-select v-model="ruleForm.inspType" placeholder="请选择新旧病害" size="small" style="width:100%" clearable>
                <el-option label="新病害" :value="0"></el-option>
                <el-option label="旧病害" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="病害描述 :" prop="problemNote" label-width="101px">
              <el-input type="textarea" maxlength="200" rows="1" v-model="ruleForm.problemNote" style="width:100%">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <el-col :span="8">
            <el-form-item label="病害照片:" prop="name" label-width="95px">
              <el-select v-model="ruleForm.inspBridge" placeholder="请选择照片" size="small" style="width:100%"
                         @change="(event)=>handleBridgeChange(event)" clearable value-key="id">
                <el-option v-for="item in bridgeOptions" :key="item.id" :label="item.ownName" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="病害位置 :" prop="problemNote" label-width="101px">
              <el-input type="textarea" maxlength="200" rows="1" v-model="ruleForm.problemNote" style="width:100%">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row justify="space-between" :gutter="20">
          <el-col :span="24">
            <el-form-item label="位置检索:">
              <div class="map_box" id="map">
                <!--  <el-input
                 v-model.trim="address"
                 id="suggestId"
                 name="ruleForm.address"
                 size="small"
                 class="item"
                 placeholder="请输入关键字"
               ></el-input> -->
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </div>


    </el-form>
  </vx-popup>
</template>

<script>
  export default {
    props: {},
    data() {
      return {
        isResouceShow: 0,
        dialogTitle: '',
        editId: '',
        dialogVisible: false,
        bridgeOptions: [],
        monthOptions: [],
        dayOptions: [],
        personOptions: [],
        deasePosOptions: {},
        ruleForm: {
          name: '',
          inspType: '',
          type: '',
          month: '',
          day: '',
          cron: '',
          inspBridges: [{
            bridge: '',
            name: [],
            inspStandard: '',
            itemUserList: []
          }]
        },
        rules: {
          name: [{
            required: true,
            message: "请输入计划名称",
            trigger: "blur"
          }],
          inspType: [{
            required: true,
            message: "请选择巡检类型",
            trigger: "change"
          }],
          type: [{
            required: true,
            message: "请选择巡检周期",
            trigger: "change"
          }],
          cycle: [{
            required: true,
            message: "请选择巡检频次",
            trigger: "change"
          }],
          execTime: [{
            required: true,
            message: "请选择执行区间",
            trigger: "change"
          }],
          validTime: [{
            required: true,
            message: "请选择有效区间",
            trigger: "change"
          }]
        },
        currentPage_sel: 1,
        pagesize_sel: 10,
        recordsTotal_sel: 0
      };
    },
    created() {
      this.queryBridgeList();
      this.queryPersonList(1);
      this.dayOptions = this.createNumberOptions(31, '日');
      this.monthOptions = this.createNumberOptions(12, '月');
    },
    methods: {
      add() {
        this.dialogVisible = true;
        this.dialogTitle = '新增问题';
        this.editId = null;
        this.emptyForm();
        this.$nextTick(function() {
          var map = new T.Map("map")
          map.centerAndZoom(new T.LngLat(120.826, 32.02), 12);
          var miniMap = new T.Control.OverviewMap({
            isOpen: true,
            size: new T.Point(100, 100)
          });
          map.addControl(miniMap);
        });
      },
      edit(val) {
        this.$refs["ruleForm"].resetFields();
        this.dialogVisible = true;
        this.dialogTitle = '编辑问题';
        this.editId = val;
        this.queryPlanById(val);
      },
      emptyForm() {
        this.$refs["ruleForm"].resetFields();
        const emptyObj = {
          name: '',
          inspType: '',
          type: '',
          month: '',
          day: '',
          cron: '',
          inspBridges: [{
            bridge: '',
            name: [],
            inspStandard: '',
            itemUserList: []
          }]
        }
        this.ruleForm = emptyObj;
      },
      queryBridgeList() {
        this.$api.bridge.AllTheBridges().then(response => {
          if (response.data.success) {
            this.bridgeOptions = response.data.data[0];
          }
        });
      },
      queryPlanById(val) {
        this.$api.insp.queryPlanById(val).then(response => {
          const _data = response.data.data;

          let _inspBridges = _data.itemList.map((item, index) => {
            let _itemUserList = item.itemUserList.map(userItem => `${userItem.userId};${userItem.userName}`);
            console.log(_itemUserList,'_itemUserList');
            let _ext1 = JSON.parse(item.ext1);
            this.handleBridgeChange(_ext1, index);
            return {
              name: [`${item.constructionId};${item.constructionName}`,
                `${item.partsId};${item.partsName}`
              ],
              inspStandard: item.inspStandard,
              bridge: _ext1,
              itemUserList: _itemUserList
            }
          });
          let _ruleForm = {
            name: _data.name,
            type: _data.type,
            cycle: _data.cycle,
            validTime: [_data.validStartTime, _data.validEndTime],
            execTime: [_data.beginExec, _data.endExec],
            inspType: _data.inspType,
            inspBridges: _inspBridges
          }
          this.ruleForm = _ruleForm;
        });
      },
      handleAddLine() {
        this.ruleForm.inspBridges.push({
          bridge: '',
          name: [],
          inspStandard: '',
          itemUserList: []
        });
      },
      handleDeleteItem(item, index) {
        this.ruleForm.inspBridges.splice(index, 1);
      },
      handleSubmit() {
        this.$refs.ruleForm.validate(async (valid) => {
          if (!valid) {
            return false;
          }
          let _userInfo = JSON.parse(localStorage.getItem("userInfo"));
          let _itemList = this.ruleForm.inspBridges.map(item => {
            let _itemUserList = item.itemUserList.map(temp => ({
              userId: temp.split(';')[0],
              userName: temp.split(';')[1],
            }));
            let _ext1 = {
              // ...item.bridge,
              id: item.bridge['id'] || '',
              name: item.bridge['name'] || '',
              lng: item.bridge['lng'] || '',
              lat: item.bridge['lat'] || '',
              bridgeTypeId: item.bridge['bridgeTypeId'] || '',
              bridgeTypeName: item.bridge['bridgeTypeName'] || '',
              province: item.bridge['provinceName'] || '',
              city: item.bridge['municipalityName'] || '',
              area: item.bridge['regionName'] || '',
              standardName: item.bridge['standardName'] || '',
            };

            return {
              name: item.name.length>0? `${item.name[0].split(';')[1]}/${item.name[1].split(';')[1]}` : '',
              constructionId: item.name.length>0?item.name[0].split(';')[0]:'',
              constructionName:item.name.length>0? item.name[0].split(';')[1]:'',
              partsId: item.name.length>0?item.name[1].split(';')[0]:'',
              partsName: item.name.length>0?item.name[1].split(';')[1]:'',
              ownId: item.bridge['id'] || '',
              ownName: item.bridge['name'] || '',
              inspPlanCfgPos: {
                ownId: item.bridge['id'] || '',
                ownName: item.bridge['name'] || '',
                lon: item.bridge['lng'] || '',
                lat: item.bridge['lat'] || '',
              },
              inspStandard: parseInt(item.inspStandard),
              itemUserList: _itemUserList,
              ext1: JSON.stringify(_ext1)
            }
          });
          let _params = {
            createUserId: _userInfo['userid'] || '',
            createUserName: _userInfo['realname'] || '',
            name: this.ruleForm.name,
            inspType: this.ruleForm.inspType,
            type: this.ruleForm.type,
            cycle: parseInt(this.ruleForm.cycle),
            beginExec: this.ruleForm.execTime[0],
            endExec: this.ruleForm.execTime[1],
            validStartTime: this.ruleForm.validTime[0],
            validEndTime: this.ruleForm.validTime[1],
            itemList: _itemList
          };

          if (this.editId) {
            _params.id = this.editId;
          }

          if (this.editId) {
            this.$api.insp.updatePlan(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '修改成功',
                  color: "success",
                  icon: "success"
                });
                this.dialogVisible = false;
                this.$emit("closeAddInspPlan");
              }
            });
          } else {
            this.$api.insp.addPlan(_params).then(response => {
              if (response.data.success) {
                this.$vs.notify({
                  text: '新增成功',
                  color: "success",
                  icon: "success"
                });
                this.dialogVisible = false;
                this.$emit("closeAddInspPlan");
              }
            });
          }
        });
      },
      cancelSubmit() {
        this.dialogVisible = false;
      },
      queryPersonList(pageIndex) {
        if (pageIndex && pageIndex === 1) {
          this.currentPage_sel = 1;
        }
        const _params = {
          pageSize: this.pagesize_sel,
          pageNum: this.currentPage_sel,
          type: '0'
        }
        this.$api.personManager.getPersonList(_params).then(response => {
          if (response.data.success) {
            this.personOptions = response.data.data;
            console.log(this.personOptions,'this.personOptions');
            this.recordsTotal_sel = response.data.recordsTotal;
          }
        });
      },
      handlePageChange_sel(currentPage) {
        this.currentPage_sel = currentPage;
        this.queryPersonList();
      },
      handleBridgeChange(event, index) {
        const _params = {
          bridgeTypeId: event['bridgeTypeId'] || '',
          pId: '-1',
          bridgeId: event['id'] || ''
        };
        this.queryConstructionModelTreeById(_params, index);
      },
      handleChangeDeasePos(event, index) {
        console.log(this.ruleForm.inspBridges[index].name);
      },
      deepDeasePosOptions(data) {
        let _arr = [];
        let _obj = {};
        data.forEach(item => {
          const _tmp = {
            ...item
          };
          if (_tmp.children && _tmp.children.length > 0) {
            _tmp.children = this.deepDeasePosOptions(_tmp.children);
          }
          _obj = {
            id: _tmp.id,
            name: _tmp.name,
            value: `${_tmp.id};${_tmp.name}`,
          }
          if (_tmp.children && _tmp.children.length > 0) {
            _obj.children = _tmp.children;
          }
          _arr.push(_obj);
        });
        return _arr;
      },
      queryConstructionModelTreeById(_params, index) {
        this.$api.bridge.queryConstructionModelTreeById(_params).then(response => {
          if (response.data.success) {
            ++this.isResouceShow;
            this.deasePosOptions[index] = this.deepDeasePosOptions(response.data.data.children);
          }
        });
      },
      createNumberOptions(length, unit) {
        let _options = [];
        for (let i = 0; i < length; i++) {
          _options.push({
            label: `${i+1}${unit}`,
            value: i + 1
          })
        }
        return _options;
      }
    }
  }

</script>
<style lang="scss" scoped>
  @import '@/assets/scss/baseColor.scss';
  @import './insp';
  .map_box{
    width: 100%;
    height: 400px;
  }
</style>
